package com.esunny.online.util;

import org.apache.commons.lang3.Validate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author hp
 */

@Component
public class SpringBeanUtil implements ApplicationContextAware {
	private  static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringBeanUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	public static <T> T getBean(String name) {
		assertContextInjected();
		return (T) getApplicationContext().getBean(name);
	}

	public static <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return getApplicationContext().getBean(requiredType);
	}

	public static <T> T getBean(String name, Class<T> clazz) {
		assertContextInjected();
		return getApplicationContext().getBean(name, clazz);
	}

	public static void clearHolder() {
		applicationContext = null;
	}

	private static void assertContextInjected() {
		Validate.validState(applicationContext != null,
				"applicationContext属性未注入", new Object[0]);
	}
}
